package com.jesse.eclgy.plug.wrapper;


import com.jesse.eclgy.plug.enums.FieldType;
import com.jesse.eclgy.plug.util.ReflectionUtils;

import java.util.*;

/**
 * @Author: jesse
 * @Date: 2023/6/3 12:45
 */
public class InsertWrapper implements IWrapper {

    /**
     * 字段列
     */
    private Map<String, Object> columns;
    /**
     * 插入的表名称
     */
    private String tableName;
    /**
     * 字段对应值
     */
    List<Object> params;


    public static InsertWrapper builder()
    {
        return new InsertWrapper();
    }

    public InsertWrapper()
    {
        this.columns = new LinkedHashMap<>();
    }

    /**
     * 查询表名
     */
    public InsertWrapper tableName(String tableName)
    {
        this.tableName = tableName;
        return this;
    }

    /**
     * 插入的字段和值
     */
    public InsertWrapper column(String field, Object value)
    {
        columns.put(field, value);
        return this;
    }

    public InsertWrapper column(String fields)
    {
        String[] fieldList = fields.split("\\,");
        for (String s : fieldList)
        {
            columns.put(s, null);
        }
        return this;
    }


    /**
     * 查询列和值
     */
    public InsertWrapper column(Map<String, Object> columns)
    {
        this.columns.putAll(columns);
        return this;
    }

    @Override
    public InsertWrapper inject(Object obj)
    {

        Map<String, Object> params = ReflectionUtils.getFieldMap(obj, FieldType.INSERT);

        this.column(params).tableName(ReflectionUtils.getTableName(obj.getClass(), false));
        return this;
    }


    @Override
    public String getSql()
    {
        StringBuilder sql = new StringBuilder();
        sql.append("INSERT INTO ");
        sql.append(this.tableName);
        StringBuilder column = new StringBuilder();
        StringBuilder value = new StringBuilder();
        this.params = new ArrayList<>();
        this.columns.forEach((k, v) -> {
            column.append(k).append(",");
            value.append("?").append(",");
            this.params.add(v);
        });
        column.deleteCharAt(column.length() - 1);
        // 删除最后一个逗号
        value.deleteCharAt(value.length() - 1);
        // 删除最后一个逗号
        sql.append("(").append(column).append(")");
        sql.append(" VALUES ");
        sql.append("(").append(value).append(")");
        return sql.toString();
    }

    @Override
    public List<Object> getParams()
    {
        return this.params;
    }
}
